package com.shu.qq.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shu.qq.common.R;
import com.shu.qq.config.security.UserSecurityService;
import com.shu.qq.data.entity.User;
import com.shu.qq.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Slf4j
@RestController
@ResponseBody
public class UserController {
    @Autowired
    UserService userService;
    @Autowired
    UserSecurityService securityService;

    @PostMapping("/register")
    public R register(@RequestBody Map<String, String> user) {
        String nickname = user.get("nickname");
        String account = user.get("account");
        String password = user.get("password");
        if (account == null) {
            return R.FAILED("账号错误");
        }
        if (nickname == null || nickname.equals("")) {
            return R.FAILED("用户名错误错误");
        }
        if (nickname.length() > 32){
            return R.FAILED("用户名过长 " + nickname.length());
        }
        if (password == null || password.equals("") || password.length() < 8) {
            return R.FAILED("密码必须大于八位");
        }
        return securityService.register(account,nickname,password);
    }

    @PostMapping("/login")
    public R login(@RequestBody Map<String,String> user, HttpServletResponse response) {
        String account = user.get("account");
        String password = user.get("password");
        if (account == null || account.trim().equals("")){
            return R.FAILED("账号为空");
        }
        if (password == null || password.trim().equals("")) {
            return R.FAILED("密码格式错误");
        }
        return securityService.login(account,password,response);


    }

    @GetMapping("/userInfo/{account}")
    public R<User> userInfo(@PathVariable("account") String account) {
        QueryWrapper<User> objectQueryWrapper = new QueryWrapper<>();
        objectQueryWrapper.eq("account", account);
        User byId = userService.getOne(objectQueryWrapper);
        if (byId == null) {
            return R.ERROR("用户不存在");
        }
        byId.setPassword("权限不足");//TODO 后面添加权限验证
        return new R<User>(200, "获取成功", byId);
    }

    @GetMapping("/addFriends/{account}")
    public R addFriends(@PathVariable("account") String account) {
        //TODO 添加好友请求
        return R.SUCCESS();
    }

    @GetMapping("/searchFriend/{account}")
    public R searchFriend(@PathVariable("account") String account){
        if (!StringUtils.hasText(account)){
            return R.FAILED("账号输入错误");
        }
        User user = userService.searchUserFromAccount(account);
        if (user == null){
            return R.FAILED("该用户不存在");
        }
        return new R(200,"查找成功",user);
    }


}
